package com.dkd.sbtz.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.dkd.common.config.RuoYiConfig;
import com.dkd.common.utils.file.FileUploadUtils;
import com.dkd.common.utils.file.MimeTypeUtils;
import com.dkd.sbtz.mapper.AssetOrderAttachmentMapper;
import com.dkd.sbtz.service.StorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.dkd.common.annotation.Log;
import com.dkd.common.core.controller.BaseController;
import com.dkd.common.core.domain.AjaxResult;
import com.dkd.common.enums.BusinessType;
import com.dkd.sbtz.domain.AssetOrderAttachment;
import com.dkd.sbtz.service.IAssetOrderAttachmentService;
import com.dkd.common.utils.poi.ExcelUtil;
import com.dkd.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 工单附件Controller
 * 
 * @author xzj
 * @date 2025-09-18
 */
@RestController
@RequestMapping("/sbtz/attachment")
public class AssetOrderAttachmentController extends BaseController
{
    @Autowired
    private IAssetOrderAttachmentService assetOrderAttachmentService;

    @Autowired
    private AssetOrderAttachmentMapper attachmentMapper;


    private static final int BUF = 8192;
    @Resource
    private StorageService storageService;
    /**
     * 查询工单附件列表
     */
    @PreAuthorize("@ss.hasPermi('sbtz:attachment:list')")
    @GetMapping("/list")
    public TableDataInfo list(AssetOrderAttachment assetOrderAttachment)
    {
        startPage();
        List<AssetOrderAttachment> list = assetOrderAttachmentService.selectAssetOrderAttachmentList(assetOrderAttachment);
        return getDataTable(list);
    }

    /**
     * 导出工单附件列表
     */
    @PreAuthorize("@ss.hasPermi('sbtz:attachment:export')")
    @Log(title = "工单附件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AssetOrderAttachment assetOrderAttachment)
    {
        List<AssetOrderAttachment> list = assetOrderAttachmentService.selectAssetOrderAttachmentList(assetOrderAttachment);
        ExcelUtil<AssetOrderAttachment> util = new ExcelUtil<AssetOrderAttachment>(AssetOrderAttachment.class);
        util.exportExcel(response, list, "工单附件数据");
    }

    /**
     * 获取工单附件详细信息
     */
    @PreAuthorize("@ss.hasPermi('sbtz:attachment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(assetOrderAttachmentService.selectAssetOrderAttachmentById(id));
    }

    /**
     * 新增工单附件
     */
    @PreAuthorize("@ss.hasPermi('sbtz:attachment:add')")
    @Log(title = "工单附件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AssetOrderAttachment assetOrderAttachment)
    {
        return toAjax(assetOrderAttachmentService.insertAssetOrderAttachment(assetOrderAttachment));
    }

    /**
     * 修改工单附件
     */
    @PreAuthorize("@ss.hasPermi('sbtz:attachment:edit')")
    @Log(title = "工单附件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AssetOrderAttachment assetOrderAttachment)
    {
        return toAjax(assetOrderAttachmentService.updateAssetOrderAttachment(assetOrderAttachment));
    }

    /**
     * 删除工单附件
     */
//    @PreAuthorize("@ss.hasPermi('sbtz:attachment:remove')")
//    @Log(title = "工单附件", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids)
//    {
//        return toAjax(assetOrderAttachmentService.deleteAssetOrderAttachmentByIds(ids));
//    }



    /** 列表 */
    @GetMapping("/{orderId}/attachments")
    public AjaxResult list(@PathVariable Long orderId) {
        return AjaxResult.success(assetOrderAttachmentService.listByOrderId(orderId));
    }

    /** 批量上传（支持文件夹：前端会传相对路径relativePaths[]，与files顺序一致） */
    @Log(title = "工单附件上传", businessType = BusinessType.INSERT)
    @PostMapping("/{orderId}/attachments/upload")
    public AjaxResult upload(@PathVariable Long orderId,
                             @RequestParam("files") MultipartFile[] files,
                             @RequestParam(value = "relativePaths", required = false) String[] relativePaths) throws Exception {
        if (files == null || files.length == 0) {
            return AjaxResult.error("未选择文件");
        }

        // 可根据需要限制大小/类型
        String baseDir = RuoYiConfig.getUploadPath(); // 若依：profile 路径
        List<AssetOrderAttachment> toSave = new ArrayList<>();

        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];

            // 存储（若依工具会按日期分目录并返回相对路径）
            String filePath = FileUploadUtils.upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
            AssetOrderAttachment a = new AssetOrderAttachment();
            a.setOrderId(orderId);
            a.setFileName(file.getOriginalFilename());
            a.setFileType(file.getContentType());
            a.setFileUrl(filePath);                    // 如：/profile/upload/2025/09/xxx.png
            a.setFileSize(file.getSize());
            if (relativePaths != null && relativePaths.length > i) {
                a.setRelativePath(relativePaths[i]);   // 如：screenshots/moduleA/img1.png
            }
            a.setUploader(getUsername());
            toSave.add(a);
        }

        assetOrderAttachmentService.saveBatch(toSave);
        return AjaxResult.success(toSave);
    }

    /** 删除附件 */
    @Log(title = "工单附件删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/attachments/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(assetOrderAttachmentService.deleteByIds(ids));
    }



    @GetMapping("/batch-download")
    public void batchDownload(@RequestParam Long orderId, HttpServletResponse resp) throws IOException {
        List<AssetOrderAttachment> list = attachmentMapper.listByOrderIds(Collections.singletonList(orderId));
        if (list == null || list.isEmpty()) {
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return;
        }
        String zipName = ("order_" + orderId + "_attachments.zip");
        resp.setContentType("application/zip");
        resp.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" +
                java.net.URLEncoder.encode(zipName, java.nio.charset.StandardCharsets.UTF_8));

        try (ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream())) {
            for (AssetOrderAttachment a : list) {
                String entryName = safeEntryName(a.getFileName(), a.getId());
                zos.putNextEntry(new ZipEntry(entryName));
                try (InputStream is = storageService.open(a.getFileUrl())) {
                    copy(is, zos);     // 核心：流式拷贝
                } catch (IOException ex) {
                    // 可选：写一个错误说明文件到 zip
                    byte[] msg = ("read error: " + ex.getMessage()).getBytes();
                    zos.write(msg);
                } finally {
                    zos.closeEntry();
                }
            }
            zos.finish();
        }
    }




    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buf = new byte[BUF];
        int n;
        while ((n = in.read(buf)) >= 0) {
            out.write(buf, 0, n);
        }
    }

    private static String safeEntryName(String fileName, Long id) {
        String name = (fileName == null || fileName.isBlank()) ? ("file_" + id) : fileName;
        // 防止 zip slip：去掉路径分隔
        name = name.replace("\\", "/");
        int idx = name.lastIndexOf('/');
        if (idx >= 0) name = name.substring(idx + 1);
        return name;
    }
}
